﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using CalibrationLibrary;

namespace CO2FixCalibration
{


    public partial class Form1 : Form
    {
        WriteCalibrationResults calibrationresults = null;
        static int I = 0;
        string measfilename;
        DirectoryStructure dir;
        //NormalDist MaxBiom;
        //NormalDist CAIdistr;

        public Form1()
        {
            InitializeComponent();

            measfilename = "input\\Measurements.txt";
            ManipCo2FixFile.Initialize("input\\CNV_Forest2.co2");
            dir = new DirectoryStructure("output");
        }

        private void SetStatus(string status)
        {
            tbStatus.Text = status;
            tbStatus.Invalidate();
            tbStatus.Update();
            tbStatus.Refresh();
            Application.DoEvents();
        }
        private void InitializeParameters(Parameters parameters, string FileName)
        {
            string[] Content = System.IO.File.ReadAllLines(FileName);

            string[] Hdr = Content[0].Split('\t');
            string[] FirstLine = Content[1].Split('\t');

            for (int h = 0; h < Hdr.Length; h++)
            {
                foreach (Parameter p in parameters.ModelParameters)
                {
                    if (p.Label == Hdr[h]) p.RunningValue = double.Parse(FirstLine[h]);
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            CalibrationLibrary.PlugIn.SetRandomSeed(0);
            
            Parameters p = new Parameters();

            p.Add(new Parameter("CAIRatiosNonCommercial", 0.4, 2.0));
            p.Add(new Parameter("CAIRatiosCommercial", 0.4, 2.0));

            p.Add(new Parameter("HY_CNV1", 0.0, 100));
            p.Add(new Parameter("HY_CNV2", 0.0, 100));
            p.Add(new Parameter("HY_CNV3", 0.0, 100));
            p.Add(new Parameter("HY_RIL1", 0.0, 100));
            p.Add(new Parameter("HY_RIL2", 0.0, 100));
            p.Add(new Parameter("HY_RIL3", 0.0, 100));

            p.Add(new Parameter("HF_CNV1", 0.4, 1));
            p.Add(new Parameter("HF_CNV2", 0.4, 1));
            p.Add(new Parameter("HF_CNV3", 0.4, 1));
            p.Add(new Parameter("HF_RIL1", 0.4, 1));
            p.Add(new Parameter("HF_RIL2", 0.4, 1));
            p.Add(new Parameter("HF_RIL3", 0.4, 1));

            p.Add(new Parameter("HarvestIntensityCNV", 0, 50));
            p.Add(new Parameter("HarvestIntensityRIL", 0, 50));
            p.Add(new Parameter("InitHarvestMortCNV", 0, 0.4));
            p.Add(new Parameter("InitHarvestMortRIL", 0, 0.4));
            p.Add(new Parameter("HarvestMort_impyrsCNV", 0, 20));
            p.Add(new Parameter("HarvestMort_impyrsRIL", 0, 20));
            
            InitializeParameters(p, "input/InitialParameters.txt");

            calibrationresults = new WriteCalibrationResults(p);

            new Calibration(p, GetProbability, int.Parse(this.tbIterations.Text), int.Parse(this.tbAdjustEvery.Text), double.Parse(this.tbAdjustFrac.Text));

             
        }
        
        double GetProbability(Parameters parameters)
        {
            // Read measurements in datasets
            double MaxInitMeas;
            ReadMeasurements.Read(measfilename, out MaxInitMeas);
            DataSet[] SimulatedBiomPerSite = new DataSet[ReadMeasurements.MeasurementsPerSite.Length];
            DataSet[] SimulatedCommercialBiomPerSite = new DataSet[ReadMeasurements.MeasurementsPerSite.Length];
            DataSet[] SimulatedCAIperSite = new DataSet[ReadMeasurements.MeasurementsPerSite.Length];

            Statistics.Initialize(ReadMeasurements.MeasurementsPerSite);
            int simlength = 300;

            // Site loop
            for (int s = 0; s < ReadMeasurements.MeasurementsPerSite.Length; s++)
            {
                 // Manipulate parameters
                string ManipCo2FileName = System.IO.Directory.GetCurrentDirectory() +"\\" + dir.SubDir(I) + ReadMeasurements.MeasurementsPerSite[s].Label + ".co2";

                //
                for (int h = 0; h <= 1; h++)
                {
                    if (ReadMeasurements.MeasurementsPerSite[s].Label == "Control" && h == 1) continue;

                    // h == 0 removes harvest
                    ManipCo2FixFile.Manipulate(h, ReadMeasurements.MeasurementsPerSite[s].Label, parameters, ManipCo2FileName, simlength);

                    // Open and export file
                    string outputfile = System.IO.Directory.GetCurrentDirectory() + "\\" + dir.SubDir(I) + "Export.txt";
                    string msg = "";
                    bool success = SimulateCO2Fix.Run(ManipCo2FileName, outputfile, out msg);

                    // Read output
                    SimulatedBiomPerSite[s] = new ReadOutput(outputfile).Read(ReadOutput.OutputType.biomass, "Biom" + ReadMeasurements.MeasurementsPerSite[s].Label);
                    SimulatedCommercialBiomPerSite[s] = new ReadOutput(outputfile).Read(new ReadOutput.OutputType[] { ReadOutput.OutputType.agathis, ReadOutput.OutputType.dipterocarp }, "CBm" + ReadMeasurements.MeasurementsPerSite[s].Label);
                    SimulatedCAIperSite[s] = new ReadOutput(outputfile).Read(ReadOutput.OutputType.CAI, "CAI" + ReadMeasurements.MeasurementsPerSite[s].Label);

                    DataSet[] Opt=null;
                    // Move file to appropriate postition along X-axis
                    if (h == 0)
                    {
                        if (ReadMeasurements.MeasurementsPerSite[s].Label != "Control")
                        {
                            // Shifts time axis according to first harvest
                            parameters = FitTimeAxis.GetHarvestYears(SimulatedBiomPerSite[s], SimulatedCommercialBiomPerSite[s], ReadMeasurements.MeasurementsPerSite[s], parameters);
                        }
                        else
                        {
                            Opt = FitTimeAxis.Optimize(ReadMeasurements.MeasurementsPerSite[s], SimulatedBiomPerSite[s], SimulatedCommercialBiomPerSite[s]);
                        }
                    }
                    else
                    {
                        Opt = FitTimeAxis.ShiftAxisAsLast(SimulatedBiomPerSite[s], SimulatedCommercialBiomPerSite[s]);
                    }
                    if (Opt != null)
                    {
                        SimulatedBiomPerSite[s] = Opt[0];
                        SimulatedCommercialBiomPerSite[s] = Opt[1];
                    }

                }
                
                

            
            }

            WriteModelMeas.Write(ReadMeasurements.MeasurementsPerSite, SimulatedBiomPerSite, System.IO.Directory.GetCurrentDirectory() + "\\" + dir.SubDir(I) + "ModelMeas.txt");

            //double Likelihood_overall =Statistics.Likelihood_overall(SimulatedBiomPerSite, SimulatedCAIperSite); ;
            double Likelihood_biomass = Statistics.Likelihood_biomass(SimulatedBiomPerSite, SimulatedCAIperSite); ;

            SetStatus("convergence = " + Math.Round(parameters.GetConvergence(),2) + " L  = " + Math.Round(Likelihood_biomass,3));

            calibrationresults.AddLine(I, parameters, Likelihood_biomass);

            calibrationresults.Print(dir.Outputdir + "//CalibationOutput.txt");

            I++;

            return Likelihood_biomass;
        }

         
        

      
    }
}
